package it.mauriziulu.android.ehttpexecutors.handler;

import it.mauriziulu.android.ehttpexecutors.cache.CacheManager;
import it.mauriziulu.android.ehttpexecutors.request.EHttpRequest;
import it.mauriziulu.android.ehttpexecutors.response.EHttpResponseContainer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.http.impl.DefaultHttpRequestFactory;
import org.apache.http.protocol.HttpContext;

import android.content.Context;
import android.net.http.AndroidHttpClient;

public class ResponseHandlerChain {

	protected AndroidHttpClient mClient;

	protected DefaultHttpRequestFactory mRequestFactory;

	private HttpContext mHttpContext;
	
	private Context mAndroidContext;

	private CacheManager mCacheManager;

	private ArrayList<EResponseHandler> mChain;

	private Iterator<EResponseHandler> mChainIterator;

	public CacheManager getCacheManager() {
		return mCacheManager;
	}

	public AndroidHttpClient getClient() {
		return mClient;
	}

	public DefaultHttpRequestFactory getRequestFactory() {
		return mRequestFactory;
	}

	public HttpContext getHttpContext() {
		return mHttpContext;
	}

	public void setCacheManager(CacheManager mCacheManager) {
		this.mCacheManager = mCacheManager;
	}

	public void setClient(AndroidHttpClient mClient) {
		this.mClient = mClient;
	}

	public void setRequestFactory(DefaultHttpRequestFactory mRequestFactory) {
		this.mRequestFactory = mRequestFactory;
	}

	public void setHttpContext(HttpContext mContext) {
		this.mHttpContext = mContext;
	}
	
	public Context getAndroidContext() {
		return mAndroidContext;
	}
	
	public void setAndroidContext(Context mAndroidContext) {
		this.mAndroidContext = mAndroidContext;
	}
	
	public ResponseHandlerChain(EResponseHandler[] chain) {
		mChain = new ArrayList<EResponseHandler>(chain.length);
		for (EResponseHandler eResponseHandler : chain) {
			mChain.add(eResponseHandler);
		}
		mChainIterator = mChain.iterator();
	}

	public void doHandle(EHttpRequest request, EHttpResponseContainer response) throws IOException {
		if (mChainIterator.hasNext()) {
			mChainIterator.next().handle(request, response, this);
		}
	}
}
